#include <curses.h>
#include <stdio.h>
#include <stdarg.h>

#include "phone.h"
#include "scrio.h"
#include "list.h"
/* #include "list2.h" */

void error(char *s,...) {
  WINDOW *errwin;
  char errstr[81];
  errwin=newwin(1,80,12,0);
  va_list arg;
  va_start(arg,s);
  vsprintf(errstr,s,arg);
  wprintw(errwin,errstr);
  va_end(arg);
  wrefresh(errwin);
  delwin(errwin);
}

void scrinit() {
  initscr();
  start_color();
  init_pair(1,7,4);
  init_pair(2,6,4);
  init_pair(3,7,0);
  raw();
  noecho();
  keypad(stdscr,TRUE);
}

void scrshut() {
  clear();
  refresh();
  noraw();
  endwin();
}

void wclrscr(WINDOW *win) {
  int r,c;
  wmove(win,0,0);
  for (r=0;r<=win->_maxy;r++) {
    for (c=0;c<=win->_maxx;c++) {
      wprintw(win," ");
    }
  }
  wmove(win,0,0);
}

void wclreol(WINDOW *win) {
  int oldx,oldy,c;
  oldx=win->_curx;
  oldy=win->_cury;
  for (c=oldx;c<=win->_maxx;c++) {
    wprintw(win," ");
  }
  wmove(win,oldy,oldx);
}

#define clreol() wclreol(stdscr)

void add(booktype &book) {
  WINDOW *addwin;
  entrytype *newent;
  addwin=newwin(6,30,10,10);
  newent=new entrytype;
  echo();
  wattrset(addwin,COLOR_PAIR(1));
  wclrscr(addwin);
  wprintw(addwin,"First name: ");
  wrefresh(addwin);
  wgetnstr(addwin,newent->first,firstmax);
  wprintw(addwin,"Last name: ");
  wrefresh(addwin);
  wgetnstr(addwin,newent->last,lastmax);
  wprintw(addwin,"Area code: ");
  wrefresh(addwin);
  wgetnstr(addwin,newent->area,areamax);
  wprintw(addwin,"Phone number: ");
  wrefresh(addwin);
  wgetnstr(addwin,newent->number,numbermax);
  wprintw(addwin,"Description: ");
  wrefresh(addwin);
  wgetnstr(addwin,newent->des,desmax);
  delwin(addwin);
  noecho();
  addentry(book,newent);
  delete newent;
}

void del(booktype &book,int &line) {
  WINDOW *win=newwin(10,30,10,10);
  char in[256];
  wattrset(win,COLOR_PAIR(1));
  echo();
  wclrscr(win);
  wprintw(win,"Delete %s %s\n",book.entries[line].first,book.entries[line].last);
  wprintw(win,"Are you sure (y,n): ");
  wrefresh(win);
  wgetstr(win,in);
  if (in[0]=='y') {
    delentry(book,line);
  }
  noecho();
  delwin(win);
}

void scrup(booktype &book,int &line) {
  if (line>0) line--;
  pbrefresh(book,line);
}

void scrdn(booktype &book,int &line) {
  if (line<book.size-1) line++;
  pbrefresh(book,line);
}

void pbrefresh(booktype &book,int line) {
  int i;
  clear();
  move(0,0);
  attrset(COLOR_PAIR(3));
  for (i=line;i<book.size && i-line<24;i++) {
    wprintw(stdscr,"%-*s %-*s (%*s)%*s %-*s\n",lastmax,book.entries[i].last,
	    firstmax,book.entries[i].first,areamax,book.entries[i].area,
	    numbermax,book.entries[i].number,desmax,book.entries[i].des);
  }
  move(24,0);
  attrset(COLOR_PAIR(2));
  wprintw(stdscr,"(a)dd (d)elete (q)uit ([) page up (]) page down");
  clreol();
  wrefresh(stdscr);
}

int getkey() {
  return(getch());
}
